package biz.datalk.industrialland.admin.modules.common.controller;

import biz.datalk.commons.utils.ip.IPUtil;
import biz.datalk.industrialland.common.result.UnifyResult;
import biz.datalk.industrialland.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author tarofang@163.com
 * @date 2024-01-15
 */
@Slf4j
@RestController
public class GitVersionController {
    public static final String GIT_PROPERTIES = "git.properties";
    public static final String SEPARATOR_SEMICOLON = ";";


    private final RedisUtil redisUtil;

    @Autowired
    public GitVersionController(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @RequestMapping("/version")
    public UnifyResult version(HttpServletRequest request) {
        String sign = request.getParameter("sign");
        if (StringUtils.isBlank(sign)) {
            return UnifyResult.fail("您没有权限访问");
        }
        String cacheSign = redisUtil.getStr("api.version.sign");
        if (!StringUtils.equals(sign, cacheSign)) {
            return UnifyResult.fail("您没有权限访问");
        }

        String remoteIp = StringUtils.trimToEmpty(IPUtil.getIpAddress(request));
        String ips = StringUtils.trimToEmpty(redisUtil.getStr("api.version.ips", ";127.0.0.1;localhost;"));
        String chkIp = StringUtils.isBlank(remoteIp) ? StringUtils.EMPTY : SEPARATOR_SEMICOLON.concat(remoteIp).concat(SEPARATOR_SEMICOLON);
        if (!StringUtils.contains(ips, chkIp)) {
            return UnifyResult.fail("无权限访问");
        }

        Properties properties = new Properties();
        try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(GIT_PROPERTIES)) {
            properties.load(resourceAsStream);
        } catch (Exception ex) {
            log.error("ERR:{}", ex.getMessage(), ex);
        }

        // 使用分号分隔，例如: git.remote.origin.url;git.branch;
        String defaultKeys = "git.remote.origin.url";
        String removeCacheKey = "api.version.remove.keys";
        String removeGitKeys = redisUtil.getStr(removeCacheKey, defaultKeys);
        String[] rmKeyArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(removeGitKeys, SEPARATOR_SEMICOLON);
        for (String rmK : rmKeyArr) {
            Object rmV = properties.remove(rmK);
            if (log.isDebugEnabled()) {
                log.debug("remove properties. [k={}, v={}]", rmK, rmV);
            }
        }

        return UnifyResult.success().setData(properties);
    }
}
